<template>
    <view>
        <RxSelectBox
            v-model="curVal"
            :disabled="readOnly"
            :placeholder="placeholder"
            :search="metadata.options.showSearch"
            :clear="metadata.options.allowClear"
            :multiple="multiple"
            :searchPlaceholder="i18n('keywords','请输入关键字')"
            :options="getOptions()"
            @change="onChange"
        ></RxSelectBox>
    </view>
</template>

<script>
import MForm from "../js/MForm";
import BaseComplex from "../js/BaseComplex.js";
import FormBase from "../js/FormBase";

import RxSelectBox from "@/components/RxSelectBox/RxSelectBox.vue";
/**
 * 下拉选择
 * https://ext.dcloud.net.cn/plugin?id=15782
 */
export default {
    name: "MSelect",
    mixins:[MForm,BaseComplex,FormBase],
    components:{
        RxSelectBox
    },
    data() {
        return {
            myValue:'',
            //下拉控件值
            curVal: "",
        }
    },
    computed: {
        multiple() {
            //多选
            return this.metadata.options.mode=='multiple' || false;
        },
        valMode() {
            //单双值
            return this.metadata.options.valMode || "single";
        },
    },
    created() {
        this.initDataSource(this.init);
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        init(){
            if(this.value){
                this.settingValue(this.value,true);
            }
        },
        onChange(value){
            //清除
            if(!value){
                this.setData('');
            }else {
                this.settingValue(value);
            }
        },
        /**
         * 设置值
         * @param option
         * 控件变化值时，option为选中的选项 {label:label,value:value,disabled:false}
         * value变化时为字符串数据
         * @param isInit
         */
        settingValue(option,isInit){
            let {valMode,mode} =this.metadata.options ;
            let {singleDefault,singleMultiple,doubleDefault,doubleMultiple} = this ;
            let method = {
                'single-default':singleDefault,//单值单选
                'single-multiple':singleMultiple,//单值多选
                'double-default':doubleDefault,//双值单选
                'double-multiple':doubleMultiple,//双值多选
            }
            method[`${valMode}-${mode}`](option,isInit);
            if(!isInit){
                this.handFieldMapping(this.curVal);
            }
        },
        singleDefault(option,isInit){
            //单值单选
            if(isInit){
                this.curVal = option ;
                return ;
            }
            this.setData(!option? "":option.value);
        },
        singleMultiple(option,isInit){
            //单值多选
            if(isInit){
                this.curVal = !option ? [] : option.split(',');
                return ;
            }
            if(!option){
                this.setData('');
                return
            }
            let arr = option.map(item=>item.value)
            this.setData(arr.toString());
        },
        doubleDefault(option,isInit){
            if (isInit) {
                if (option && option.includes('{') && option.includes('}')) {
                    let obj = new Function(`return ${option}`)()
                    this.curVal = obj.value.split(',')[0];
                    return;
                } else {
                    this.setDefaultValue(option);
                    return ;
                }
            }
            //双值单选
            if(!option){
                this.setData('');
                return;
            }
            this.setData(JSON.stringify({value:option.value,label:option.label}));
        },
        doubleMultiple(option,isInit){
            //双值多选
            if(isInit){
                if(!option || option.length==0){
                    this.curVal = []
                    return ;
                }
                if(option.includes('{') && option.includes('}')){
                    let obj = new Function(`return ${option}`)()
                    this.curVal = obj.value.split(',');
                }else {
                    this.setDefaultValue(option);
                }
                return ;
            }
            if(!option || option.length===0){
                this.curVal = []
                this.setData('')
                return
            }
            let labelArr = [],valueArr= [];
            for(let item of option){
                labelArr.push(item.label)
                valueArr.push(item.value)
            }
            this.setData(JSON.stringify({
                label:labelArr.toString(),
                value:valueArr.toString()
            }))
        },
        /**
         * 双值时 默认值 改变时的数据处理；
         * @param defaultValue
         */
        setDefaultValue(defaultValue){
            let { valMode,mode } = this.metadata.options ;
            let options = this.getOptions();
            if(valMode === 'double') {//双值
                if(mode === 'default'){//单选
                    this.curVal = defaultValue ;
                    let obj = options.find(item=>item.value === defaultValue);
                    if(obj){
                        let {label,value} = obj ;
                        let json =JSON.stringify({label,value})
                        this.updateValue(json)
                        //触发初始化事件
                        this.executeInitCustomQuery(json);
                    }
                }else if( mode === 'multiple') {//多选
                    let val = defaultValue.split(',')
                    this.curVal = val;
                    let labelArr = [],valueArr = [];
                    let count = 0 ;
                    for (let item of options){
                        if(count >= val.length){ break }
                        if(val.includes(item.value)){
                            labelArr.push(item.label)
                            valueArr.push(item.value)
                            count += 1 ;
                        }
                    }
                    let json =JSON.stringify({
                        label:labelArr.toString(),
                        value:valueArr.toString()
                    })
                    this.updateValue(json);
                    //触发初始化事件
                    this.executeInitCustomQuery(json);
                }
            }
        },
    },
    watch: {
        "value":function (val){
            this.settingValue(val,true);
        },
        options: {
            handler(val) {
                if (val) {
                    this.settingValue(this.value,true);
                }
            },
            deep: true
        }
    },
}
</script>

<style scoped>

</style>
